package com.steam.org.service.impl;

import com.steam.basic.service.impl.BaseServiceImpl;
import com.steam.basic.util.Md5Utils;
import com.steam.basic.util.StrUtils;
import com.steam.org.domain.Employee;
import com.steam.org.mapper.EmployeeMapper;
import com.steam.org.service.IEmployeeService;
import com.steam.user.domain.Logininfo;
import com.steam.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Employee employee) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        //保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        super.save(employee);
        if (employee.getRoleId() != null){
            employeeMapper.addEmployeeRole(employee);
        }
    }

    @Override
    public void remove(Long id) {
        //删除登录信息logininfo
        Employee employee = employeeMapper.loadById(id);
        logininfoMapper.remove(employee.getLogininfo_id());
        //删除employee信息
        super.remove(id);
        employeeMapper.delEmployeeRoleByEmpId(id);
    }

    @Override
    public void update(Employee employee) {
        //通过empId删除中间表数据 - 外键挂链要注意
        employeeMapper.delEmployeeRoleByEmpId(employee.getId());
        //再添加员工的角色信息到中间表：employee - eid roleId
        if(employee.getRoleId()!=null){
            employeeMapper.addEmployeeRole(employee);
        }
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        super.update(employee);
        //获取登录信息id
        Long logininfoId = employeeMapper.loadById(employee.getId()).getLogininfo_id();
        //创建logininfo
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);//id,type ,state
        //将新的数据覆盖旧的数据
        BeanUtils.copyProperties(employee,logininfo);//5个数据新的 - 用户名，邮箱，电话，盐值，密码
        //重置logininfoId
        logininfo.setId(logininfoId);
        logininfoMapper.update(logininfo);
    }

    @Override
    public List<Employee> findByShopId(Long shopId) {
        return employeeMapper.findByShopId(shopId);
    }
}
